<!-- components/G2LineChart.vue -->
<template>
  <div>
    <!-- <div class="name">订单数 (近七日)</div> -->
    <div class="name">收益 (近七日)</div>
    <div ref="chartContainer" class="g2-chart"></div>
  </div>
</template>

<script>
import { Chart } from "@antv/g2";

export default {
  props: {
    chartData: {
      type: Array,
      default: () => [],
    },
    chartConfig: {
      type: Object,
      default: () => ({
        xField: "day",
        yField: "dayAmount",
        lineStyle: {
          stroke: "#1890ff",
          lineWidth: 2,
        },
        pointStyle: {
          fill: "white",
          stroke: "#1890ff",
        },
      }),
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  watch: {
    chartData: {
      handler(newVal) {
        if (this.chart) {
          this.chart.changeData(newVal);
        }
      },
      deep: true,
    },
  },
  methods: {
    initChart() {
      // 销毁旧实例
      if (this.chart) {
        this.chart.destroy();
      }

      // 创建新实例
      this.chart = new Chart({
        container: this.$refs.chartContainer,
        autoFit: true,
        height: 300,
        axis: {
          x: {
            title: false
          },
          y: {
            title: false,
          },
        },
      });

      // 数据绑定与图形配置
      this.chart
        .data(this.chartData)
        .encode("x", this.chartConfig.xField)
        .encode("y", this.chartConfig.yField)
        .scale("x", { range: [0, 1] })
        .scale("y", { domainMin: 0, nice: true });

      // 绘制折线
      this.chart
        .line()
        .style("stroke", this.chartConfig.lineStyle.stroke)
        .style("lineWidth", this.chartConfig.lineStyle.lineWidth)
        .label();

      // 绘制点
      this.chart
        .point()
        .style("fill", this.chartConfig.pointStyle.fill)
        .style("stroke", this.chartConfig.pointStyle.stroke)
        .tooltip(false);

      // 渲染图表
      this.chart.render();

      // 响应式适配
      window.addEventListener("resize", this.handleResize);
    },
    handleResize() {
      if (this.chart) {
        this.chart.forceFit();
      }
    },
  },
  beforeDestroy() {
    // 清理资源
    if (this.chart) {
      this.chart.destroy();
      window.removeEventListener("resize", this.handleResize);
    }
  },
};
</script>

<style scoped>
.g2-chart {
  width: 100%;
  height: 300px;
}
.name {
  margin: 35px;
  margin-left: 15px;
}
</style>
